package com.hqd.ch03.v41.web.utils;

import com.hqd.ch03.v41.utils.StringUtils;

import java.nio.charset.Charset;

public abstract class UriUtils {
    public static String decode(String source, String encoding) {
        return StringUtils.uriDecode(source, Charset.forName(encoding));
    }

    public static String decode(String source, Charset charset) {
        return StringUtils.uriDecode(source, charset);
    }

    public static String extractFileExtension(String path) {
        int end = path.indexOf('?');
        int fragmentIndex = path.indexOf('#');
        if (fragmentIndex != -1 && (end == -1 || fragmentIndex < end)) {
            end = fragmentIndex;
        }
        if (end == -1) {
            end = path.length();
        }
        int begin = path.lastIndexOf('/', end) + 1;
        int paramIndex = path.indexOf(';', begin);
        end = (paramIndex != -1 && paramIndex < end ? paramIndex : end);
        int extIndex = path.lastIndexOf('.', end);
        if (extIndex != -1 && extIndex >= begin) {
            return path.substring(extIndex + 1, end);
        }
        return null;
    }

    public static String encodePathSegment(String segment, String encoding) {
        return encode(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
    }

    private static String encode(String scheme, String encoding, HierarchicalUriComponents.Type type) {
        return HierarchicalUriComponents.encodeUriComponent(scheme, encoding, type);
    }

}
